<?php
namespace app\controller\api\info;


use app\BaseController;
use app\common\repositories\info\AdPackageRepository;
use app\common\repositories\info\AdTaskRecordRepository;
use app\common\repositories\info\AdTaskRepository;
use app\common\repositories\info\AdTaskRepository as repository;
use think\App;
use think\exception\ValidateException;

class AdTask extends BaseController{

    protected repository $repository;

    public function __construct(App $app,repository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    public function lst()
    {
        [$page,$limit] = $this->request->page();
        $where = [];
        return success($this->repository->getApiLst($where,$page,$limit));
    }


    public function userLst()
    {
        [$page,$limit] = $this->request->page();
        $where = $this->request->params([
            ['type',1]
        ]);
        return success($this->repository->getUserLst($where,$page,$limit));
    }


    public function index()
    {
        $user = request()->userInfo();
        $balance = $user->balance;

        $needToPublishAdCount = systemConfig('need_to_publish_ad_count') ?: 0;
        $co = app()->make(AdTaskRepository::class)->getCount(['status'=>2,'uid'=>$user->uid]);
        $needToPublishAdCount -= $co;

        // 获取广告收益还差多少条发布广告
        $needShareCount = max($needToPublishAdCount, 0);

        /**@var $adTask AdTaskRecordRepository**/
        $adTask = app()->make(AdTaskRecordRepository::class);


        $validShare = $adTask->getSearch()->where(['uid'=>$user->uid,'is_valid'=>1,'type'=>1])->count();
        $validView = $adTask->getSearch()->where(['uid'=>$user->uid,'is_valid'=>1,'type'=>0])->count();


        return success(compact('balance','needShareCount','validShare','validView'));
    }


    public function create()
    {
        $params = $this->request->params(['package_id','title','images','content']);
        $this->validate($params,[
            'title|任务标题'=>'require',
            'content|任务描述'=>'require',
            'images|图片'=>'require|array',
        ]);

        if(!$params['package_id']){
            throw new ValidateException('请选择套餐');
        }
        $params['uid'] = request()->uid();
        return success(['config'=>$this->repository->create($params)]);
    }


    public function update($id)
    {
        $params = $this->request->params(['title','images','content']);
        $task = $this->repository->getWhere(['uid'=>request()->uid(),'task_id'=>$id]);
        if(!$task)
            throw new ValidateException('数据不存在');

        if($task->status == 3){
            throw  new ValidateException('任务已结束');
        }

        $this->validate($params,[
            'title|任务标题'=>'require',
            'content|任务描述'=>'require',
            'images|图片'=>'require|array',
        ]);

        $params['images'] = join(',',$params['images']);
        $params['avatar'] = $params['images'][0];

        $params['status'] = 1;

        $task->save($params);
        return success('编辑成功');
    }


    public function getTime()
    {
        $time = systemConfig('watch_ad_get_money_time') ? : 1;
        return success(compact('time'));
    }


    public function share($id)
    {
        $this->repository->share($id);
        return success('分享成功');
    }


    public function record()
    {
        $taskId = input('task_id','');
        $shareUid = input('share_uid','');
        $openid = input('openid','');

        $this->repository->record($taskId,$shareUid,$openid);
        return success('记录成功');
    }


    public function detail($id)
    {

        // 0 发布者本人浏览 1 其他人浏览
        $status = input('status',0);

        $detail = $this->repository->getWhere(['task_id'=>$id],'*',['user']);

        if(!$detail){
            throw new ValidateException('任务已下架');
        }

        $this->repository->incrNumberField($id,'view');


        if($status && !in_array($detail->status,[2,3])){
            throw new ValidateException('任务审核中');
        }

        return success($detail);
    }


    /**
     * 套餐列表
     */
    public function packageLst()
    {
        /**@var $make AdPackageRepository**/
        $make = app()->make(AdPackageRepository::class);
        $list = $make->getSearch()->select();

       // var_dump($list);

        $isNotSd = app()->make(AdTaskRepository::class)->getSearch()->where(['uid'=>request()->uid()])->whereIn('status',[1,2,3])->count();

        $newList = [];

        foreach ($list as $key=>$item){
            if(!$item['sd_status']){
                $newList[] = $item;
                continue;
            };
            if(!$isNotSd && $item['sd_status'] == 1){
                continue;
            }

            if($isNotSd && $item['sd_status'] == 2){
                continue;
            }

            $newList[] = $item;
        }

        return success($newList);
    }



    public function adConfig()
    {
        $user = request()->userInfo();

        $userCanPublish = systemConfig('user_can_publish_ad') ? : 0;

        if(!$user->member){
            // 是否可以进入广告
            $canIntoTask = false;
            // 是否可以发布广告
            $canPublishAd = !!$userCanPublish;
        }else{
            $canIntoTask = true;
            $canPublishAd = true;
        }

        $needToPublishAdCount = systemConfig('need_to_publish_ad_count') ?: 0;
        $co = app()->make(AdTaskRepository::class)->getCount(['status'=>2,'uid'=>$user->uid]);
        $needToPublishAdCount -= $co;

        // 获取广告收益还差多少条发布广告
        $needToPublishAdCount = max($needToPublishAdCount, 0);


        $courseMember = $user->course_member;
        $member = $user->member;

        return success(compact('canIntoTask','needToPublishAdCount','canPublishAd','member','courseMember'));
    }


}